<template>
  <div class="main">
    <a-form id="formLogin" layout="vertical" class="user-layout-login">
      <a-form-item v-bind="validateInfos.username">
        <a-input
          size="large"
          v-model:value="modelRef.username"
          placeholder="请输入账户"
          style="width: 100%"
          allow-clear
        >
          <template #prefix>
            <user-outlined class="prefixIcon" />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item v-bind="validateInfos.password">
        <a-input-password v-model:value="modelRef.password" size="large" placeholder="请输入密码">
          <template #prefix>
            <lock-outlined class="prefixIcon" />
          </template>
        </a-input-password>
        <span class="errorClass" v-if="isLoginError">账户或密码错误</span>
      </a-form-item>
      <a-form-item style="padding-top: 53px">
        <a-button
          size="large"
          type="primary"
          html-type="submit"
          class="login-button"
          :loading="loginBtn"
          @click="handleSubmit"
        >
          登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from 'vue';
import { getSmsCaptcha } from '@/api/user/login';
import { message, notification } from 'ant-design-vue';
import { useForm } from '@ant-design-vue/use';
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import { AxiosError } from 'axios';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { LOGIN } from '@/store/modules/user/actions';
import jsencrypt from '@/utils/jsencrypt-rsa';

import { userMenu } from '@/api/user/login';
import { routes } from '@/router/index';
import ls from '@/utils/local-storage';
import { depthEach } from '@/utils/tree';
import { MenuDataItem } from '@/router/typing';
export default defineComponent({
  name: 'Login',
  setup() {
    const router = useRouter();
    const store = useStore();
    const state = reactive({
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,

      time: 60,
      smsSendBtn: false,
    });
    const routesMap = {};
    depthEach(routes, item => {
      routesMap[item.name] = item;
    });

    const modelRef = reactive({
      rememberMe: true,
      username: '',
      password: '',
      mobile: '',
      captcha: '',
    });

    const rulesRef = reactive({
      rememberMe: undefined,
      username: [{ required: true, message: '请输入用户名', type: 'string' }],
      password: [
        { required: true, message: '请输入密码', type: 'string', trigger: ['blur', 'change'] },
      ],
      mobile: [
        {
          required: true,
          // pattern: /^1[34578]\d{9}$/,
          message: '请输入正确的手机号',
          trigger: ['blur', 'change'],
        },
      ],
      captcha: [{ required: true, message: '请输入验证码' }],
    });
    const { validateInfos, validate, resetFields } = useForm(modelRef, rulesRef);

    const handleTabClick = (key: string) => {
      state.customActiveKey = key;
      resetFields();
    };

    const requestFailed = (err: AxiosError) => {
      state.isLoginError = true;
      notification.error({
        message: '错误',
        description: ((err.response || {}).data || {}).errorMessage || '请求出现错误，请稍后再试',
        duration: 4,
      });
    };

    // 获取菜单信息
    const getMenuInfo = () => {
      return userMenu()
        .then(res => {
          const dfs = (treeData, callback) => {
            return treeData.map(item => {
              const map = data => {
                const cData = callback && callback(data);
                if (cData.children) {
                  cData.children = cData.children.map(child => map(child));
                }
                return cData;
              };
              return map(item);
            });
          };
          const newData = dfs(res.data, item => {
            const route = {
              children: item.children,
              name: item.attributes.routeName,
              path: item.attributes.url,
              redirect: undefined,
              meta: {
                icon: routesMap[item.attributes.routeName]?.meta?.icon,
                lock: true,
                title: item.name,
              },
            };
            item.attributes.redirect && (route.redirect = item.attributes.redirect);
            return route;
          });
          ls.set('user_menu', newData);
          router.push({ path: '/' });
          // 延迟 1 秒显示欢迎信息
          setTimeout(() => {
            notification.success({
              message: '欢迎',
              description: '欢迎回来',
            });
          }, 1000);
          state.isLoginError = false;
        })
        .catch(err => {
          console.log('err=', err);
        });
    };

    const loginSuccess = () => {
      getMenuInfo();
    };

    const getCaptcha = (e: Event) => {
      e.preventDefault();

      validate('mobile')
        .then(values => {
          state.smsSendBtn = true;

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60;
              state.smsSendBtn = false;
              window.clearInterval(interval);
            }
          }, 1000);

          const hide = message.loading('验证码发送中..', 0);
          getSmsCaptcha({ mobile: values.mobile })
            .then(res => {
              setTimeout(hide, 2500);
              notification.success({
                message: '提示',
                description: '验证码获取成功，您的验证码为：' + res.captcha,
                duration: 8,
              });
            })
            .catch(err => {
              setTimeout(hide, 1);
              clearInterval(interval);
              state.time = 60;
              state.smsSendBtn = false;
              requestFailed(err);
            });
        })
        .catch(err => {
          console.log('err', err);
        });
    };

    const handleSubmit = (e: Event) => {
      e.preventDefault();
      const validateNames =
        state.customActiveKey === 'tab1' ? ['username', 'password'] : ['mobile', 'captcha'];
      state.loginBtn = true;
      validate(validateNames)
        .then(values => {
          const rsa = new jsencrypt();
          values.password = rsa.encryptLong2(values.password);
          rsa.destroyed();
          store
            .dispatch(`user/${LOGIN}`, values)
            .then(() => {
              loginSuccess();
            })
            .catch(err => {
              requestFailed(err);
            })
            .finally(() => {
              state.loginBtn = false;
            });
        })
        .catch((/*err*/) => {
          // 屏蔽错误处理
          // requestFailed(err);
          state.loginBtn = false;
        });
    };
    // this.loginBtn = false;
    // this.stepCaptchaVisible = false;

    return {
      ...toRefs(state),
      modelRef,
      validateInfos,

      handleTabClick,
      handleSubmit,
      getCaptcha,
    };
  },
  components: {
    UserOutlined,
    LockOutlined,
  },
});
</script>

<style lang="less" scoped>
.main {
  //   padding-top: 5%;
}
.user-layout-login {
  label {
    font-size: 14px;
  }
  .errorClass {
    position: absolute;
    top: 40px;
    right: 0px;
    width: 118px;
    margin-top: 14px;
    color: #ffbbbb;
    font-weight: 400;
    font-size: 13px;
    font-family: Microsoft YaHei;
    line-height: 18px;
  }
  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    width: 320px;
    height: 40px;
    background: #1faaf2;
    border-radius: 20px;
  }

  .user-login-other {
    margin-top: 24px;
    line-height: 22px;
    text-align: left;

    .item-icon {
      margin-left: 16px;
      color: @disabled-color;
      font-size: 24px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: @primary-color;
      }
    }

    .register {
      float: right;
    }
  }
  .prefixIcon {
    color: #ffffff;
    font-size: @font-size-base;
    font-size: 20px;
  }
}
:deep(.ant-input-clear-icon) {
  color: #ffffff;
  font-size: 20px;
}
:deep(.ant-input-password-icon) {
  color: #ffffff;
  font-size: 20px;
}
:deep(.ant-input-affix-wrapper-lg) {
  height: 42px;
  margin: 0 auto;
  border-color: #ffffff;
  border-radius: 25px;
}
:deep(.ant-form) {
  width: 320px;
  margin: 0 auto;
  margin-top: 20px;
}
</style>
